package com.hm.service.impl.ydcg;

import com.alibaba.fastjson2.JSON;
import com.hm.service.entity.ydcg.*;
import com.hm.service.service.main.PullCaseService;
import com.hm.service.utils.JsonUtils;
import com.hm.service.utils.TimeUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * 拉取案件
 */
@Service
public class PullCaseServiceImpl implements PullCaseService {
    private static final Logger logger = LoggerFactory.getLogger(PullCaseServiceImpl.class);

    @Qualifier("OkHttpClient")
    private final OkHttpClient okHttpClient;

    public PullCaseServiceImpl(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    @Override
    public List<CaseBean> getSelfDispCaseList(String lastUpdateTime) {
        String ydcg = "www.ydzhcg.com";
        String ReqPatrolListUrl = "https://" + ydcg + ":7888/dex/api/data-model/get_patrol_deal";
        //token
        String token = getToken();
        //当前时间
        String currentTime = TimeUtils.getCurrentTime();
        //ReqPatrolListUrl：自行处理全量接口
        CaseRespBean caseInfo = getCaseInfo(lastUpdateTime, currentTime, 1, token, ReqPatrolListUrl);
        List<CaseBean> caseList = new ArrayList<>();
        if (caseInfo == null) {
            return caseList;
        }
        //有几页就循环请求几次-->一次性拉取
        int totalPages = caseInfo.totalPages;
        logger.warn("自行处理案件共有{}条，共有{}页", caseInfo.totalCount, totalPages);
        List<CaseBean> result = caseInfo.result;
        if (result == null || result.isEmpty()) {
            return caseList;
        }
        caseList.addAll(result);//添加请求数据
        for (int i = 2; i <= totalPages; i++) {
            //第二页开始
            CaseRespBean caseRespBean = getCaseInfo(lastUpdateTime, currentTime, i, token, ReqPatrolListUrl);
            if (caseRespBean != null && caseRespBean.result != null) {
                caseList.addAll(caseRespBean.result);//添加请求数据
            }
        }
        return caseList;
    }

    @Override
    public List<CaseBean> getProfessionCaseList(String lastUpdateTime) {
        String ydcg = "www.ydzhcg.com";
        String ReqCaseListUrl = "https://" + ydcg + ":7888/dex/api/data-model/getrecinfo";
        //token
        String token = getToken();
        //当前时间
        String currentTime = TimeUtils.getCurrentTime();
        //ReqPatrolListUrl：自行处理全量接口
        CaseRespBean caseInfo = getCaseInfo(lastUpdateTime, currentTime, 1, token, ReqCaseListUrl);
        List<CaseBean> caseList = new ArrayList<>();
        if (caseInfo == null) {
            return caseList;
        }
        //有几页就循环请求几次-->一次性拉取
        int totalPages = caseInfo.totalPages;
        logger.warn("专业部门处理案件共有{}条，共有{}页", caseInfo.totalCount, totalPages);
        List<CaseBean> result = caseInfo.result;
        if (result == null || result.isEmpty()) {
            return caseList;
        }
        caseList.addAll(result);//添加请求数据
        for (int i = 2; i <= totalPages; i++) {
            //第二页开始
            CaseRespBean caseRespBean = getCaseInfo(lastUpdateTime, currentTime, i, token, ReqCaseListUrl);
            if (caseRespBean != null && caseRespBean.result != null) {
                caseList.addAll(caseRespBean.result);//添加请求数据
            }
        }
        //补充案件信息
        for (CaseBean caseBean : caseList) {
            replenish(caseBean);
        }
        logger.warn("专业部门处理案件处理完成，共有：{}条", caseList.size());
        return caseList;
    }

    /**
     * 获取案件信息
     *
     * @param startTime startTime
     * @param endTime   endTime
     * @param pageIndex pageIndex
     * @param token     token
     * @param reqUrl    reqUrl
     * @return CaseRespBean
     */
    private CaseRespBean getCaseInfo(String startTime, String endTime, int pageIndex, String token, String reqUrl) {
        int pageSize = 100;//每页展示案件的数量
        ReqCaseParamsBean paramsBean = new ReqCaseParamsBean();
        paramsBean.start_time = startTime;//开始时间
        paramsBean.end_time = endTime;//结束时间
        paramsBean.pageIndex = pageIndex;//页码
        paramsBean.pageSize = pageSize;//每页展示的数量
        //开始请求
        String reqParams = JSON.toJSONString(paramsBean);
        //构建请求体
        RequestBody body = RequestBody.create(reqParams, MediaType.get("application/json; charset=UTF-8"));
        Request request = new Request.Builder()//
                .addHeader("Authorization", "bearer " + token)//token认证
                .url(reqUrl)//请求连接
                .post(body)//请求体
                .build();//构建
        //同步请求
        try (Response response = okHttpClient.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                return null;
            }
            String jsonString = responseBody.string();
            CaseRespBean caseRespBean = JSON.parseObject(jsonString, CaseRespBean.class);
            if (caseRespBean == null) {
                return null;
            }
            int totalCount = caseRespBean.totalCount;
            //计算有多少页-->totalPages根据每页展示的数量变化
            caseRespBean.totalPages = (totalCount + pageSize - 1) / pageSize;
            return caseRespBean;
        } catch (Exception e) {
            logger.error("获取案件异常: {}", e.getMessage());
        }
        return null;
    }

    private void replenish(CaseBean caseBean) {
        String PicHost = "https://www.ydzhcg.com:7888/eUrbanMIS/";
        String ydcg = "www.ydzhcg.com";
        String ReqSupplementUrl = "https://" + ydcg + ":7888/eUrbanMIS/openapi/v2/downstream/recmediainfo";
        if (caseBean == null) {
            return;
        }
        String eventCode = caseBean.eventcode;
        String reqUrl = ReqSupplementUrl + "?taskNum=" + eventCode;
        Request request = new Request.Builder().url(reqUrl).build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            ResponseBody body = response.body();
            if (body == null) {
                //请求失败
                logger.error("任务号：{}body为空", eventCode);
                return;
            }
            String jsonString = body.string();
            if (!JsonUtils.isJson(jsonString)) {
                logger.error("任务号：{}返回数据异常{}", eventCode, jsonString);
                return;
            }
            ReplenishBean replenishBean = JSON.parseObject(jsonString, ReplenishBean.class);
            List<ReplenishBean.Data.RecInfo.Medias> mediaList = replenishBean.data.recInfo.medias;
            String disposePerson = replenishBean.data.recInfo.disposePerson;//当前处理部门
            String actDefName = replenishBean.data.recInfo.actDefName;//当前处理人
            StringJoiner stringJoiner = new StringJoiner(",");//图片信息
            for (ReplenishBean.Data.RecInfo.Medias medias : mediaList) {
                String mediaURL = medias.mediaURL.replaceAll("null", PicHost);
                stringJoiner.add(mediaURL);
            }
            //开始对CaseBean补充复制
            caseBean.fileUrls = stringJoiner.toString();//图片
            caseBean.currentDeptName = disposePerson;//当前处理部门
            caseBean.currentDealPeopleName = actDefName;//当前处理人
        } catch (Exception e) {
            logger.error("{}获取补充案件失败：Exception:{}", eventCode, e.getMessage());
        }
    }

    /**
     * 获取token
     *
     * @return token
     */
    private String getToken() {
        String ydcg = "www.ydzhcg.com";
        String ReqTokenUrl = "https://" + ydcg + ":7888/dex/oauth/extras/token";
        //请求参数
        AuthorizationParamsBean paramsBean = new AuthorizationParamsBean();
        paramsBean.client_id = "10001";
        paramsBean.client_secret = "dd91a0180a";
        paramsBean.grant_type = "client_credentials";
        String reqParams = JSON.toJSONString(paramsBean);
        //构建请求体
        RequestBody body = RequestBody.create(reqParams, MediaType.get("application/json; charset=UTF-8"));
        Request request = new Request.Builder()//
                .url(ReqTokenUrl)//请求连接
                .post(body)//请求体
                .build();//构建
        //同步请求
        try (Response response = okHttpClient.newCall(request).execute()) {
            ResponseBody resBody = response.body();
            if (resBody != null) {
                String jsonString = resBody.string();
                AccessTokenBean accessTokenBean = JSON.parseObject(jsonString, AccessTokenBean.class);
                String token = accessTokenBean.access_token;
                logger.warn("获取英德城管accessToke成功：{}", token);
                return token;
            } else {
                logger.error("accessToke获取失败onResponse为null！！");
            }
        } catch (Exception e) {
            logger.error("accessToke获取失败Exception: {}", e.getMessage());
        }
        return "";
    }


}
